package com.mayisoftware.mayioa.common.impl.zip;

import com.mayisoftware.mayioa.common.impl.utils.file.EncodingDetect;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import java.io.*;
import java.util.Enumeration;

public class UnZipFile {

    public static String unZipFile(File zipFile, String descDir)throws IOException {

        String fileName =zipFile.getName();
        String fileNameNoExt = fileName.substring(0,fileName.lastIndexOf("."));

        String unzipDir = descDir+File.separatorChar+fileNameNoExt+File.separatorChar;
        File pathFile = new File(unzipDir);
        if(!pathFile.exists()){
            pathFile.mkdirs();
        }

        fileName = fileName.substring(0,fileName.lastIndexOf("."));
        ZipFile zip = new ZipFile(zipFile,"GBK");

        for(Enumeration entries = zip.getEntries(); entries.hasMoreElements();){
            ZipEntry entry =(ZipEntry)entries.nextElement();
            String zipEntryName = entry.getName();
            InputStream in =zip.getInputStream(entry);
            String outPath =(unzipDir+zipEntryName).replaceAll("\\*", "/");;

            //判断路径是否存在,不存在则创建文件路径

            File file = new File(outPath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }

            //判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
            if(file.isDirectory()){
                continue;
            }
//            OutputStreamWriter oStreamWriter = new OutputStreamWriter(new FileOutputStream(file), "utf-8");


            OutputStream out = new FileOutputStream(file);
            byte[] buf1 = new byte[1024];
            int len;
            while((len=in.read(buf1))>0){
                out.write(buf1,0,len);
            }

            in.close();
            out.close();
        }

        return  unzipDir;
    }
}
